//本地缓存，过期时间为毫秒

export const yStorage = {
  lSet: (key, value, exp = null) => {
    if (exp === null) {
      return localStorage.setItem(key, JSON.stringify({ data: value }));
    }
    let expTime = new Date().getTime() + exp;
    return localStorage.setItem(key, JSON.stringify({ data: value, exp: expTime }));
  },
  lGet: (key) => {
    let data = localStorage.getItem(key) || '';
    if (data) {
      data = JSON.parse(data);
      if (data.exp !== undefined && data.exp < new Date().getTime()) {
        localStorage.removeItem(key);
        data = '';
      } else {
        data = data.data;
      }
    }
    return data;
  },
  lDel: (key) => {
    return localStorage.removeItem(key);
  },
  sSet: (key, value, exp = null) => {
    if (exp === null) {
      return sessionStorage.setItem(key, JSON.stringify({ data: value }));
    }
    let expTime = new Date().getTime() + exp;
    return sessionStorage.setItem(key, JSON.stringify({ data: value, exp: expTime }));
  },
  sGet: (key) => {
    let data = sessionStorage.getItem(key) || '';
    if (data) {
      data = JSON.parse(data);
      if (data.exp !== undefined && data.exp < new Date().getTime()) {
        sessionStorage.removeItem(key);
        data = '';
      } else {
        data = data.data;
      }
    }
    return data;
  },
  sDel: (key) => {
    return sessionStorage.removeItem(key);
  }
};
window.yStorage = yStorage;
export default yStorage;
